#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#define MAXLINE 4096

static int arg_num = 0;
static char** arg_value;

void* file_up(void* args) {
    int   sockfd, len;
    char  buffer[MAXLINE];
    struct sockaddr_in  servaddr;
    FILE *fq;
    char **argv = (char **)args;
    // printf("client file_up:%d, %s\n", arg_num, arg_value[1]);
    if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        printf("clinet create socket error: %s(errno: %d)\n", strerror(errno),errno);
        return 0;
    }
    // usleep(4 * 1000 * 1000);
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(6666);
    if(arg_num == 2) {
        printf("clinet use default ip:192.168.0.96\n");
        if( inet_pton(AF_INET, "192.168.0.96", &servaddr.sin_addr) <= 0) {
            printf("clinet inet_pton error for 192.168.0.96\n");
            return 0;
        }
    } else {
        if( inet_pton(AF_INET, arg_value[arg_num - 2], &servaddr.sin_addr) <= 0) {
            printf("clinet inet_pton error for %s\n",arg_value[arg_num -2]);
            return 0;
        }
    }
    if(connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0) {
        printf("connect error: %s(errno: %d)\n",strerror(errno),errno);
        return 0;
    }
    if( ( fq = fopen(arg_value[arg_num - 1],"rb") ) == NULL ) {
        printf("clinet open file failed.\n");
        close(sockfd);
        exit(1);
    }
    printf("clinet send file:%s\n", arg_value[arg_num - 1]);
    bzero(buffer,sizeof(buffer));
    while(!feof(fq)){
        len = fread(buffer, 1, sizeof(buffer), fq);
        // printf("clinet read file:%s, size:%d\n", buffer, len);
        if(len != write(sockfd, buffer, len)){
            printf("clinet write:%s\n", buffer);
            break;
        }
    }
    close(sockfd);
    fclose(fq);
}

int main(int argc, char** argv) {
    pthread_t tid;
    if(argc < 2) {
        printf("clinet usage: ./client <ipaddress> <file>\n");
        return 0;
    }
    arg_num = argc;
    arg_value = argv;
    if(pthread_create(&tid, NULL, file_up, NULL)) {
        printf("clinet pthread_create failed:%s\n", strerror(errno));
    }
    pthread_join(tid, NULL);
    printf("clinet over.\n");
    return 0;
}
